const ProductModel = require('../models/productModel');
const { success, error, notFound } = require('../utils/response');

const ProductController = {
  // 获取所有商品
  getAllProducts: async (req, res) => {
    try {
      const { categoryId, search, limit = 10 } = req.query;
      const products = await ProductModel.getAllProducts({
        categoryId,
        search,
        limit: parseInt(limit)
      });
      success(res, products);
    } catch (err) {
      console.error(err);
      error(res, '获取商品列表失败', 500);
    }
  },
  
  // 获取商品详情
  getProductById: async (req, res) => {
    try {
      const product = await ProductModel.getProductById(req.params.id);
      
      if (!product) {
        return notFound(res, '商品不存在');
      }
      
      success(res, product);
    } catch (err) {
      console.error(err);
      error(res, '获取商品详情失败', 500);
    }
  },
  
  // 创建商品 (需要管理员权限)
  createProduct: async (req, res) => {
    try {
      // 这里应该添加权限检查中间件
      const { category_id, name, description, price, stock, is_active = true } = req.body;
      const image = req.file ? req.file.path : null;
      
      if (!category_id || !name || !price || stock === undefined) {
        return error(res, '分类ID、商品名称、价格和库存为必填项', 400);
      }
      
      const productId = await ProductModel.createProduct({
        category_id,
        name,
        description,
        price,
        stock,
        image,
        is_active
      });
      
      success(res, { id: productId }, '商品创建成功', 201);
    } catch (err) {
      console.error(err);
      error(res, '创建商品失败', 500);
    }
  },
  
  // 更新商品 (需要管理员权限)
  updateProduct: async (req, res) => {
    try {
      // 这里应该添加权限检查中间件
      const productId = req.params.id;
      const { name, description, price, stock, is_active } = req.body;
      const image = req.file ? req.file.path : null;
      
      const updateData = {
        name: name || req.body.name,
        description: description || req.body.description,
        price: price || req.body.price,
        stock: stock || req.body.stock,
        image: image || req.body.image,
        is_active: is_active || req.body.is_active
      };
      
      const successUpdate = await ProductModel.updateProduct(productId, updateData);
      
      if (!successUpdate) {
        return error(res, '更新商品失败', 500);
      }
      
      success(res, null, '商品更新成功');
    } catch (err) {
      console.error(err);
      error(res, '更新商品失败', 500);
    }
  },
  
  // 删除商品 (需要管理员权限)
  deleteProduct: async (req, res) => {
    try {
      // 这里应该添加权限检查中间件
      const successDelete = await ProductModel.deleteProduct(req.params.id);
      
      if (!successDelete) {
        return notFound(res, '商品不存在或删除失败');
      }
      
      success(res, null, '商品删除成功');
    } catch (err) {
      console.error(err);
      error(res, '删除商品失败', 500);
    }
  }
};

module.exports = ProductController;